import React from 'react';
import { connect } from 'react-redux'
import moment from 'moment'
import {messages, deepFullCopy, queryCurrencyPrecision} from "share/common";
import {Icon, Table} from "antd"

import Condition from 'components/condition'
const { If, Else } = Condition;

import 'styles/expense-report/components/expense-calendar-table.scss'

class ExpenseCalendarTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      columns: [],
      dataSource: [],
      totalDays: 0,
      totalAmount: 0,
      baseCurrency: props.baseCurrency,
      applicant: props.applicant
    };
    this.baseCurrencyPrecision = queryCurrencyPrecision(props.baseCurrency);
  }

  componentWillMount() {
    const { dataSource } = this.props;
    this.processData(dataSource);
  };

  componentWillReceiveProps(nextProps) {
    this.processData(nextProps.dataSource);
  };

  sortData = (a,b) => {
    if(a.ownerOID.localeCompare(b.ownerOID) === 0){
      if(a.expenseTypeOID.localeCompare(b.expenseTypeOID) === 0){
        return a.createdDate - b.createdDate;
      }else{
        return a.expenseTypeOID.localeCompare(b.expenseTypeOID);
      }
    }else{
      return a.ownerOID.localeCompare(b.ownerOID);
    }
  };

  processData = (dataSource) => {
    const { applicant } = this.state;
    dataSource.sort(this.sortData);
    let data = [];
    let amountList = {}; //所有费用的发生日期列表
    let expenseAmountList = {}; //每费用归属人每费用类型的 费用日期列表
    let employeeAmountList = {}; //每费用归属人的 费用日期列表
    let expenseTotal = 0;  //每费用类型汇总
    let employeeTotal = 0; //每费用归属人汇总
    let total = 0; //总金额
    dataSource.forEach((d, index, dataSource) => {
      let thisItem = deepFullCopy(d);
      let nextItem = deepFullCopy(dataSource[index+1]);
      let createdDate = moment(d.createdDate).format("YYYY-MM-DD ddd");
      total += d.baseAmount;
      amountList[createdDate] = (amountList[createdDate] || 0) + d.baseAmount;
      if(index === dataSource.length - 1){
        expenseTotal += d.baseAmount;
        expenseAmountList[createdDate] = (expenseAmountList[createdDate] || 0) + d.baseAmount;
        data.push({
          fullName: d.owner.fullName,
          ownerOID: d.ownerOID,
          employeeId: d.employeeId,
          expenseTypeName: d.expenseTypeName,
          expenseTypeOID: d.expenseTypeOID,
          ...expenseAmountList,
          total: expenseTotal
        });
        employeeTotal += d.baseAmount;
        employeeAmountList[createdDate] = (employeeAmountList[createdDate] || 0) + d.baseAmount;
        data.push({
          fullName: d.owner.fullName,
          ownerOID: d.ownerOID,
          employeeId: d.employeeId,
          expenseTypeName: messages('expense-parent-report.key176')/*每日汇总*/,
          sumRow: true,
          ...employeeAmountList,
          total: employeeTotal
        });
        data.push({
          fullName: messages('expense-parent-report.key177')/*汇总*/,
          employeeId: "",
          expenseTypeName: messages('expense-parent-report.key177')/*汇总*/,
          totalSum: true,
          ownerOID: d.ownerOID,
          ...amountList,
          total: total
        });
      }else{
        if(thisItem.ownerOID === nextItem.ownerOID){
          employeeTotal += d.baseAmount;
          employeeAmountList[createdDate] = (employeeAmountList[createdDate] || 0) + d.baseAmount;
          if(thisItem.expenseTypeOID === nextItem.expenseTypeOID){
            expenseTotal += d.baseAmount;
            expenseAmountList[createdDate] = (expenseAmountList[createdDate] || 0) + d.baseAmount;
          }else{
            expenseTotal += d.baseAmount;
            expenseAmountList[createdDate] = (expenseAmountList[createdDate] || 0) + d.baseAmount;
            data.push({
              fullName: d.owner.fullName,
              ownerOID: d.ownerOID,
              employeeId: d.employeeId,
              expenseTypeName: d.expenseTypeName,
              expenseTypeOID: d.expenseTypeOID,
              ...expenseAmountList,
              total: expenseTotal
            });
            expenseTotal = 0;
            expenseAmountList = {};
          }
        }else{
          expenseTotal += d.baseAmount;
          expenseAmountList[createdDate] = (expenseAmountList[createdDate] || 0) + d.baseAmount;
          data.push({
            fullName: d.owner.fullName,
            ownerOID: d.ownerOID,
            employeeId: d.employeeId,
            expenseTypeName: d.expenseTypeName,
            expenseTypeOID: d.expenseTypeOID,
            ...expenseAmountList,
            total: expenseTotal
          });
          expenseTotal = 0;
          expenseAmountList = {};

          employeeTotal += d.baseAmount;
          employeeAmountList[createdDate] = (employeeAmountList[createdDate] || 0) + d.baseAmount;
          data.push({
            fullName: d.owner.fullName,
            ownerOID: d.ownerOID,
            employeeId: d.employeeId,
            expenseTypeName: messages('expense-parent-report.key176')/*每日汇总*/,
            sumRow: true,
            ...employeeAmountList,
            total: employeeTotal
          });
          employeeTotal = 0;
          employeeAmountList = {};
        }
      }
    });

    //计算费用归属人行合并 rowSpan.length为费用归属人的个数
    let rowSpan = [];
    let i = 0;
    data.forEach(item => {
      if(!item.sumRow) i++;
      else{
        rowSpan.push(++i);
        i = 0;
      }
    });

    let columnsArr = [];
    //只有1位费用归属人时，隐藏每日汇总行并将行合并行数-1
    if(rowSpan.length === 1){
      data.splice(data.length - 2, 1);
      rowSpan[0] = rowSpan[0] - 1;
    }
    //有多位费用归属人或费用归属人不是单据所属人时才显示归属人列
    if(rowSpan.length > 1 || (data.length && data[data.length-1].ownerOID.localeCompare(applicant))){
      columnsArr.push({
        title: messages('expense-parent-report.key173')/*归属人*/,
        dataIndex: 'fullName',
        key: 'fullName',
        align: "center",
        width: 120,
        fixed: true,
        render: (value, row, index) => {
          let obj= {
            children: <span style={{whiteSpace: "pre"}}>{`${row.fullName}\n${row.employeeId}`}</span>,
            props: {colSpan: 1, rowSpan: 0}
          };
          if(index === data.length - 1){
            obj.props.rowSpan = 1;
            obj.props.colSpan = 2;
          }
          let sum = 0;
          rowSpan.forEach(r => {
            if(index === sum)
              obj.props.rowSpan = r;
            sum += r;
          });

          return obj;
        }
      })
    }
    columnsArr.push({
      title: messages("common.expense.type")/*费用类型*/,
      key: 'expenseTypeName',
      dataIndex: 'expenseTypeName',
      width: 150,
      fixed: "left",
      render: (value, row, index) => {
        if(index === data.length - 1 && (rowSpan.length !== 1 || data[data.length-1].ownerOID.localeCompare(applicant))) {
          return {
            children: value,
            props: {colSpan: 0}
          }
        }else{
          return <span style={{color: row.sumRow ? "#FAAD14" : "normal"}}>{value}</span>
        }
      }
    });

    Object.keys(amountList).sort().map((item, index) => {
      let width = Object.keys(amountList).length > 7 ? {width: 120} : {};
      columnsArr.push({
        title: <span style={{whiteSpace: "pre"}}>{item.split(" ").join('\n')}</span>,
        dataIndex: item,
        key: `${item}`,
        ...width,
        align: "center",
        ...width,
        render: (value, row, index) => {
          return <span className='money-cell'
                       style={{color: row.sumRow ? "#FAAD14" : "#4B8DFF", fontWeight: row.totalSum ? 800 : "normal", cursor: "pointer"}}
                       onClick={() => this.filterData(row, "items", item)}>
            {value ? this.filterMoney(value, this.baseCurrencyPrecision) : (row.sumRow ? Number(0).toFixed(2) : "")}
          </span>
        }
      })
    });

    columnsArr.push({
      title: messages('expense-parent-report.key177')/*汇总*/,
      key: 'total',
      dataIndex: "total",
      fixed: "right",
      width: 100,
      render: (value, row, index) => {
        return <span className='money-cell'
                     style={{color: row.sumRow ? "#FAAD14" : (row.totalSum ? "#52C41A" : "#4B8DFF"), cursor: "pointer"}}
                     onClick={() => this.filterData(row,"total")}>
          <b>{this.filterMoney(value, this.baseCurrencyPrecision) || (row.sumRow ? "0.00" : "")}</b>
        </span>
      }
    });
    this.setState({
      dataSource: data,
      columns: columnsArr,
      totalDays: Object.keys(amountList).length,
      totalAmount: total
    })
  };

  filterData = (row, type, date) => {
    let filterCondition = {
      owner: [],
      ownerOID: [],
      expenseType: [],
      expenseTypeOID: [],
      date: []
    };
    if(type === "items"){
      if(row.sumRow){
        filterCondition.ownerOID = [row.ownerOID];
        filterCondition.owner = [row.fullName];
        filterCondition.date = [date];
      }else if(row.totalSum){
        filterCondition.date = [date];
      }else{
        filterCondition.ownerOID = [row.ownerOID];
        filterCondition.owner = [row.fullName];
        filterCondition.expenseType = [row.expenseTypeName];
        filterCondition.expenseTypeOID = [row.expenseTypeOID];
        filterCondition.date = [date];
      }
    }
    if(type === "total"){
      if(row.sumRow){
        filterCondition.ownerOID = [row.ownerOID];
        filterCondition.owner = [row.fullName];
      }else if(row.totalSum){
      }else{
        filterCondition.ownerOID = [row.ownerOID];
        filterCondition.owner = [row.fullName];
        filterCondition.expenseType = [row.expenseTypeName];
        filterCondition.expenseTypeOID = [row.expenseTypeOID];
      }
    }
    this.props.filterData(filterCondition);
  };

  render() {
    const { columns, dataSource, totalDays, totalAmount, baseCurrency } = this.state;
    return (
      <Table columns={columns}
             className={`expense-calendar-table fixed-table-width`}
             dataSource={dataSource}
             title={() => (
               <div className="expense-table-title">
                 {messages('expense-parent-report.key178')/*时间*/}：&nbsp;
                 <b>{totalDays}&nbsp;</b>&nbsp;
                 {messages('expense-parent-report.key179')/*天*/}
                 <span className="ant-divider"/>
                 {messages('common.total.amount')/*总金额*/}：&nbsp;
                 <b>{baseCurrency} {this.filterMoney(totalAmount, this.baseCurrencyPrecision)}</b>
                 <a className={"f-right"} onClick={() => this.props.toggleMode()}><Icon type="calendar"/>{messages('expense-parent-report.key180')/*退出日历*/}</a>
               </div>
             )}
             scroll={{x: totalDays > 7 ? 120 * totalDays : true}}
             bordered={true}
             pagination={false}/>
    )
  }
}

ExpenseCalendarTable.propsType = {
  dataSource: React.PropTypes.array,
  toggleMode: React.PropTypes.func,
  baseCurrency: React.PropTypes.string,
  applicant: React.PropTypes.string,
  filterData: React.PropTypes.func
};

ExpenseCalendarTable.defaultProps = {

};

function mapStateToProps(state) {
  return { }
}

export default connect(mapStateToProps)(ExpenseCalendarTable)
